<template>
  <avue-crud
      ref="crud"
      v-model="form"
      class="crud-table"
      :option="tableOption"
      :data="list"
      :page.sync="page"
      :search.sync="searchForm"
      :table-loading="loading"
      :header-cell-class-name="() => 'crud-table-head'"
      :cell-class-name="() => 'crud-cell'"
      @search-change="searchChange"
      @refresh-change="getList()"
      @current-change="currentChange"
      @size-change="handleSizeChange"
      @hook:mounted="$ele.tableMount($refs.crud)"
      @hook:beforeDestroy="$ele.tableDestroy($refs.crud)"
  >
    <template #name="{ row }">
      <span v-if="row.level === '1'"> {{ row.name }}</span>
      <span v-else></span>
    </template>
    <template #name2="{ row }">
      <template v-if="row.level === '2'">
        <span style="position: relative;left: -20px;">{{ row.name }}</span>
      </template>
      <template v-else-if="row.level === '3'">
        <span>{{ handleTypeName(row.name) }}</span>
      </template>
      <template v-else>
        <span></span>
      </template>
    </template>
    <template #count="{ row }">
      <template v-if="row.level === '1'">
        <el-button type="warning">
          <span>{{ row.count }}</span>
        </el-button>
      </template>
      <template v-else-if="row.level === '2'">
        <span style="color: #ff9000">{{ row.count }}</span>
      </template>
      <template v-else>
        <span>{{ row.count }}</span>
      </template>
    </template>
    <template #searchMenu="{ size }">
      <el-button type="primary" :size="size" @click="searchChange">查 询</el-button>
      <el-button type="primary" plain :size="size" @click="resetForm">重 置</el-button>
    </template>
    <template #menuLeft="{ size }">
      <el-button type="primary" :size="size" @click="handleExcel">导出</el-button>
    </template>
  </avue-crud>
</template>
<script>
import {tableOption} from './tableOption'
import {warnFrequencyAnalysis, getWarnModuleList, getShipList, getTenantList} from '@/api/warnmessage'

import {objFindDateArray2String} from '@/utils/util'
import {mapState} from 'vuex'

export default {
  data() {
    return {
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      list: [],
      loading: true,
      form: {},
      levelDic: [
        {
          label: '一级告警',
          value: '1'
        },
        {
          label: '二级告警',
          value: '2'
        },
        {
          label: '三级告警',
          value: '3'
        }
      ],
      warnModuleArr: [],
      tenantArr: [],
      shipArr: []
    }
  },
  computed: {
    ...mapState('user', ['tenantId']),
    tableOption() {
      return tableOption.call(this)
    }
  },
  created() {
    this.initDict()
  },
  methods: {
    getWarnModule() {
      getWarnModuleList().then(res => {
        this.warnModuleArr = res.result
      })
    },
    handleTypeName(value) {
      let name = ''
      const obj = this.warnModuleArr.find(i => i.warningModelCode == value)
      if (obj != undefined) {
        name = obj.warningModelName
      }
      return name
    },
    formatterValue(value, dicCode, dic) {
      const res = dic || this.$store.getters['dict/getDictByCode'](dicCode)
      return (res.find(i => i.value == value) && res.find(i => i.value == value).lable) || value || '--'
    },
    resetForm() {
      this.$refs.crud.searchReset()
      this.page.currentPage = 1
      this.getList()
    },
    async initDict() {
      Promise.all([this.getWarnModule(), this.getTenant(), this.getShip()]).then(async () => {
        // 处理时间
        const time = this.$moment(new Date()).format("YYYY-MM-DD");
        this.searchForm.createTime = [time.slice(0,4)+ '-01-01' + ' 00:00:00', time + ' 23:59:59']

        this.getList()
      })
    },

    getTenant() {
      this.searchForm.shipId = ''
      getTenantList({superviseTenantId: this.tenantId}).then(res => {
        if (res.result) {
          this.tenantArr = res.result.map(item => {
            return {
              label: item.name,
              value: item.id,
            }
          })
        } else {
          this.tenantArr = []
        }
      })
    },
    getShip(value) {
      this.searchForm.shipId = ''
      getShipList({
        superviseTenantId: this.tenantId,
        tenantId: value || '',
      }).then(res => {
        if (res.result) {
          this.shipArr = res.result.map(item => {
            return {
              label: item.name,
              value: item.id,
            }
          })
        } else {
          this.shipArr = []
        }
      })
    },
    currentChange(val) {
      this.page.currentPage = val
      this.getList()
      this.$refs.curd?.doLayout()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getList()
      this.$refs.curd?.doLayout()
    },

    getList() {
      this.loading = true
      const params = objFindDateArray2String({
        pageNumber: this.page.currentPage,
        pageSize: this.page.pageSize,
        ...this.searchForm,
        startTime: this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined,
        endTime: this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined,
        createTime: undefined,
      })
      warnFrequencyAnalysis(params)
          .then(response => {
            this.list = response.result.records
            this.page.total = response.result.total
          })
          .catch(() => {
          })
          .finally(() => {
            this.loading = false
            this.$refs.crud?.doLayout()
          })
    },
    searchChange(form, done) {
      this.page.currentPage = 1
      this.getList(form || '')
      done && done()
    },
    handleExcel() {
      const params = {
        ...this.searchForm,
        createTime: undefined,
        startTime: this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined,
        endTime: this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined,
      };
      this.$http
          .request({
            url: "/warnings/warning/warnFrequencyAnalysisExport",
            method: "get",
            params: params,
            responseType: "blob", // 这里最重要,不要去掉
          })
          .then((res) => {
            const startTime = this.$moment(params.startTime).format('YYYY年MM月DD日')
            const endTime = this.$moment(params.endTime).format('YYYY年MM月DD日')
            // this.downloadFileByBlob(res.data, `告警频次分析导出数据${startTime}-${endTime}.xls`);
            this.downloadFileByBlob(res.data, params.startTime?`告警频次分析导出数据${startTime}-${endTime}.xls`:'告警频次分析导出数据.xls')
          });
    },
    // 导出
    downloadFileByBlob(blob, fileName = "file") {
      const blobUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.download = fileName || "defaultName";
      link.style.display = "none";
      link.href = blobUrl;
      // 触发点击
      document.body.appendChild(link);
      link.click();
      // 移除
      document.body.removeChild(link);
    },
  },
}
</script>
